package admin

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"jwgin/model/mysql"
	"jwgin/service"
)

type ActivitySignIn struct {
}

func (l *ActivitySignIn) Routers(Router *gin.RouterGroup) {
	Router.GET("sign", l.get)
	Router.GET("sign/record", l.record)
	Router.POST("sign/role", l.postRule)
}

func (ActivitySignIn) get(c *gin.Context) {
	count, size, offset := pages(c)
	db := service.G.Model(mysql.Activity{}).
		Joins("JOIN `company` ON company.id = activity.comid").
		Joins("JOIN `activity_template` ON activity_template.id = activity.activity_template_id").
		Joins("LEFT JOIN `activity_sign_rule` ON activity_sign_rule.sid = activity.id")
	//时间筛选
	startTime := c.Query("startTime")
	endTime := c.Query("endTime")
	if startTime != "" && endTime != "" {
		db = db.Where(" activity.addtime > ? AND activity.addtime < ? ", startTime, endTime)
	}
	list := []map[string]interface{}{}
	db.Select("title,template_name,rule_bean,activity.*").Count(&count).Offset(offset).Limit(size).Order("id DESC").Scan(&list)
	RespList(c, count, list)
}
func (ActivitySignIn) post(c *gin.Context) {}
func (ActivitySignIn) postRule(c *gin.Context) {
	data := &struct {
		Sid      int `json:"sid" binding:"required"`
		RuleBean int `json:"rule_bean" binding:"required"`
	}{}

	if err := c.ShouldBind(data); err != nil {
		RespErr(c, err)
		return
	}

	var count int64
	err := service.G.Table("activity_sign_rule").Where("sid = ? ", data.Sid).Count(&count).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		RespErr(c, fmt.Errorf("数据库查询出错:%v", err))
		return
	}

	if count == 0 {
		service.G.Table("activity_sign_rule").Create(data)
	} else {
		service.G.Table("activity_sign_rule").Where("sid = ? ", data.Sid).Updates(data)
	}

	RespSucc(c, nil)
}

//签到历史
func (ActivitySignIn) record(c *gin.Context) {
	count, size, offset := pages(c)
	db := service.G.Model(mysql.ActivitySignRecord{}).
		Joins("JOIN `user` ON user.id = activity_sign_record.uid").
		Joins("JOIN `activity`  ON activity.id = activity_sign_record.activity_id").
		Joins("JOIN `company` ON company.id = user.comid")

	//时间筛选
	startTime := c.Query("startTime")
	endTime := c.Query("endTime")
	if startTime != "" && endTime != "" {
		db = db.Where(" activity_sign_record.addtime > ? AND activity_sign_record.addtime < ? ", startTime, endTime)
	}

	//按公司查找
	if title := c.Query("title"); title != "" {
		db = db.Where("company.account = ?", title)
	}

	if username := c.Query("username"); username != "" {
		db = db.Where("user.account = ?", username)
	}

	list := []map[string]interface{}{}
	db.Select("activity_name,user.username,activity_sign_record.*").Count(&count).
		Offset(offset).
		Limit(size).
		Order("id DESC").
		Scan(&list)
	RespList(c, count, list)
}
